/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.admin.controller;

// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.esotericsoftware.minlog.Log;
import com.yami.shop.bean.model.Book;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.admin.util.SecurityUtils;
import com.yami.shop.service.BookService;
import lombok.AllArgsConstructor;
import com.yami.shop.common.response.ServerResponseEntity;

// import org.hibernate.validator.internal.util.logging.Log_.logger;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 公告管理
 *
 * @author hzm
 * @date
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/shop/book")
public class BookController {

    // private final Logger logger = LoggerFactory.getLogger(BookController.class);
    
    private final BookService bookService;

    /**
     * 分页查询
     *
     * @param page   分页对象
     * @param book 公告管理
     * @return 分页数据
     */
    @GetMapping("/page")
    public ServerResponseEntity<IPage<Book>> getBookPage(PageParam<Book> page, Book book) {

        log.info("分页查询book.getTitle：{}", book.getTitle()); //是url里的参数
        // log.info("Book::getTitle：{}", Book::getTitle);
        
        IPage<Book> bookPage = bookService.page(
                page, 
                new LambdaQueryWrapper<Book>()
                    .eq(book.getStatus() != null, Book::getStatus, book.getStatus())
                    .eq(book.getIsTop()!=null,Book::getIsTop,book.getIsTop())
                    // .like(book.getTitle() != null, Book::getTitle, book.getTitle())
                    .nested(
                            book.getTitle() != null, 
                            wrapper -> wrapper
                            .like(Book::getTitle, book.getTitle())
                            .or()
                            .like(Book::getContent, book.getTitle())
                    )
                    .orderByDesc(Book::getUpdateTime)
            );

        System.out.println("分页结果 => " + bookPage.toString());
        
        return ServerResponseEntity.success(bookPage);
    }


    /**
     * 通过id查询公告管理
     *
     * @param id id
     * @return 单个数据
     */
    @GetMapping("/info/{id}")
    public ServerResponseEntity<Book> getById(@PathVariable("id") Long id) {
        return ServerResponseEntity.success(bookService.getById(id));
    }

    /**
     * 新增公告管理
     *
     * @param book 公告管理
     * @return 是否新增成功
     */
    @SysLog("新增公告管理")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('shop:book:save')")
    public ServerResponseEntity<Boolean> save(@RequestBody @Valid Book book) {
        book.setShopId(SecurityUtils.getSysUser().getShopId());
        if (book.getStatus() == 1) {
            book.setUpdateTime(new Date());
        }
        book.setUpdateTime(new Date());
        bookService.removeBookList();
        return ServerResponseEntity.success(bookService.save(book));
    }

    /**
     * 修改公告管理
     *
     * @param book 公告管理
     * @return 是否修改成功
     */
    @SysLog("修改公告管理")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('shop:book:update')")
    public ServerResponseEntity<Boolean> updateById(@RequestBody @Valid Book book) {
        Book oldBook = bookService.getById(book.getId());
        if (oldBook.getStatus() == 0 && book.getStatus() == 1) {
            book.setUpdateTime(new Date());
        }
        // logger.info("修改公告管理：{}", book);
        book.setUpdateTime(new Date());
        bookService.removeBookList();
        bookService.removeBookById(book.getId());
        return ServerResponseEntity.success(bookService.updateById(book));
    }

    /**
     * 通过id删除公告管理
     *
     * @param id id
     * @return 是否删除成功
     */
    @SysLog("删除公告管理")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('shop:book:delete')")
    public ServerResponseEntity<Boolean> removeById(@PathVariable Long id) {
        bookService.removeBookList();
        bookService.removeBookById(id);
        return ServerResponseEntity.success(bookService.removeById(id));
    }

}
